<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <text class="nav-title">我的工单</text>
    </view>

    <!-- 创建工单按钮 -->
    <view class="create-btn-container">
      <button class="create-btn" @click="gotoCreateTicket">
        <i class="fa fa-plus"></i> 创建新工单
      </button>
    </view>
    
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <scroll-view scroll-x="true" class="filter-scroll" enable-flex>
        <view class="filter-items">
          <button 
            :class="{'active': currentFilter === 'all'}" 
            @click="changeFilter('all')"
            class="filter-btn"
          >
            全部
          </button>
          <button 
            :class="{'active': currentFilter === 0}" 
            @click="changeFilter(0)"
            class="filter-btn"
          >
            待处理
          </button>
          <button 
            :class="{'active': currentFilter === 1}" 
            @click="changeFilter(1)"
            class="filter-btn"
          >
            处理中
          </button>
          <button 
            :class="{'active': currentFilter === 2}" 
            @click="changeFilter(2)"
            class="filter-btn"
          >
            已处理
          </button>
          <button 
            :class="{'active': currentFilter === 3}" 
            @click="changeFilter(3)"
            class="filter-btn"
          >
            已结算
          </button>
          <button 
            :class="{'active': currentFilter === 4}" 
            @click="changeFilter(4)"
            class="filter-btn"
          >
            待审核
          </button>
          <button 
            :class="{'active': currentFilter === 5}" 
            @click="changeFilter(5)"
            class="filter-btn"
          >
            已归档
          </button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 工单列表 -->
    <view class="workorder-list">
      <!-- 加载中状态 -->
      <view class="loading-state" v-if="isLoading">
        <text class="loading-spinner">⏳</text>
        <text class="loading-text">加载工单中...</text>
      </view>

      <!-- 数据列表 -->
      <view 
        class="workorder-item" 
        v-for="item in filteredWorkorders" 
        :key="item.id"
        @click="gotoWorkorderDetail(item.id)"
        v-else-if="filteredWorkorders.length > 0"
      >
        <view class="item-header">
          <text class="item-title">{{ item.title || '无标题工单' }}</text>
          <text class="item-status" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </text>
        </view>
        
        <text class="item-desc">{{ item.des || '无工单描述' }}</text>
        
        <view class="item-footer">
          <text class="item-time">{{ formatTime(item.createTime) }}</text>
          
          <view class="item-actions">
            <text class="handler-info" v-if="item.employeeName">
              <i class="fa fa-user-o"></i> {{ item.employeeName }}
            </text>
            
            <!-- 查看评价按钮 -->
            <button 
              v-if="isSettledStatus(item.status) && item.feedbackStatus === 1" 
              class="view-rate-btn" 
              @click.stop="gotoEvaluatePage"
            >
              <i class="fa fa-eye"></i> 查看评价
            </button>
            
            <!-- 评价按钮 -->
            <button 
              v-if="isSettledStatus(item.status) && item.feedbackStatus === 0" 
              class="rate-btn" 
              @click.stop="gotoRating(item.id, item.title, item.employeeName)"
            >
              <i class="fa fa-star-o"></i> 评价
            </button>
            
            <!-- 修改按钮 -->
            <button 
              v-if="item.status === 0" 
              class="edit-btn" 
              @click.stop="gotoEditTicket(item)"
            >
              <i class="fa fa-pencil"></i> 修改
            </button>
            
            <!-- 删除按钮 -->
            <button 
              v-if="item.status === 0" 
              class="delete-btn" 
              @click.stop="showDeleteConfirm(item.id)"
            >
              <i class="fa fa-trash-o"></i> 删除
            </button>
            
            <!-- 支付按钮 -->
            <button 
              v-if="item.status === 2" 
              class="pay-btn" 
              @click.stop="handlePay(item.id)"
              :loading="isPaying[item.id]"
            >
              <i class="fa fa-credit-card"></i> 支付
            </button>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <text class="empty-icon">📭</text>
        <text class="empty-text">{{ getEmptyStateText() }}</text>
      </view>
    </view>

    <!-- 底部导航组件 -->
    <bottom-nav :current-path="currentPagePath"></bottom-nav>
  </view>
</template>

<script>
import request from '@/api/request.js';
import bottomNav from '@/pages/components/bottom-nav/bottom-nav.vue';

export default {
  components: { bottomNav },
  data() {
    return {
      currentFilter: 'all',
      workorders: [],
      isLoading: false,
      currentPagePath: '/pages/User/workorder/workorder',
      statusConfig: {
        0: { text: '待处理', class: 'status-pending' },
        1: { text: '处理中', class: 'status-processing' },
        2: { text: '已处理', class: 'status-handled' },
        3: { text: '已结算', class: 'status-settled' },
        4: { text: '待审核', class: 'status-pending-review' },
        5: { text: '已归档', class: 'status-archived' }
      },
      isDeleting: false,
      isPaying: {}, // 记录每个工单的支付加载状态
      payAmount: 0, // 存储后端计算的最终支付金额（如1250.00）
      userInfo: {}, // 当前登录用户信息
      totalCount: 0, // 工单总数
      pageNo: 1, // 当前页码
      pageSize: 10, // 每页条数
      hasMore: true // 是否还有更多数据
    };
  },
  
  computed: {
    // 按筛选条件过滤工单列表
    filteredWorkorders() {
      return this.currentFilter === 'all' 
        ? this.workorders 
        : this.workorders.filter(item => Number(item.status) === Number(this.currentFilter));
    }
  },
  
  // 页面加载时初始化
  onLoad() {
    this.userInfo = uni.getStorageSync('userInfo') || {};
    this.loadWorkorders();
  },
  
  // 页面显示时刷新数据
  onShow() {
    uni.$on('workorderUpdated', this.handleWorkorderUpdate);
    this.loadWorkorders();
  },
  
  // 页面卸载时移除事件监听
  onUnload() {
    uni.$off('workorderUpdated', this.handleWorkorderUpdate);
  },
  
  // 下拉刷新触发
  onPullDownRefresh() {
    this.pageNo = 1;
    this.hasMore = true;
    this.loadWorkorders(true).then(() => {
      uni.stopPullDownRefresh();
    });
  },
  
  // 上拉加载更多触发
  onReachBottom() {
    if (this.hasMore && !this.isLoading) {
      this.pageNo++;
      this.loadWorkorders();
    }
  },
  
  methods: {
    // 工单更新事件（支付/删除后刷新列表）
    handleWorkorderUpdate() {
      this.pageNo = 1;
      this.loadWorkorders();
    },
    
    // 判断是否为已结算状态（仅已结算可评价）
    isSettledStatus(status) {
      return Number(status) === 3;
    },
    
    // 加载工单列表
    async loadWorkorders(refresh = false) {
      if (!this.userInfo?.id) {
        this.isLoading = false;
        this.workorders = [];
        uni.showToast({ title: '请先登录', icon: 'none' });
        return Promise.resolve();
      }
      
      this.isLoading = true;
      try {
        const requestParams = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          type: 0,
          status: this.currentFilter === 'all' ? null : Number(this.currentFilter),
          userId: this.userInfo.id
        };
        
        const response = await request.postJson(
          '/api/workOrderInfo/queryPageList',
          requestParams,
          true
        );
        
        if (response?.records) {
          const { records, total, pages } = response;
          this.totalCount = total;
          this.workorders = refresh ? records : [...this.workorders, ...records];
          this.hasMore = this.pageNo < pages;
          
          if (refresh && records.length === 0) {
            uni.showToast({ title: '暂无工单数据', icon: 'none' });
          }
        } else {
          this.workorders = refresh ? [] : this.workorders;
          uni.showToast({ title: '未查询到工单数据', icon: 'none' });
        }
      } catch (error) {
        this.workorders = refresh ? [] : this.workorders;
        uni.showToast({ title: error.msg || '加载失败，请重试', icon: 'none' });
        console.error('工单加载错误:', error);
      } finally {
        this.isLoading = false;
      }
      
      return Promise.resolve();
    },
    
    // 获取空状态提示文本
    getEmptyStateText() {
      return this.currentFilter === 'all' 
        ? '暂无工单' 
        : `暂无${this.getStatusText(this.currentFilter)}的工单`;
    },
    
    // 切换筛选条件
    changeFilter(filter) {
      this.currentFilter = filter;
      this.pageNo = 1;
      this.hasMore = true;
      this.loadWorkorders(true);
    },
    
    // 获取工单状态样式
    getStatusClass(status) {
      return this.statusConfig[Number(status)]?.class || 'status-unknown';
    },
    
    // 获取工单状态文本
    getStatusText(status) {
      return this.statusConfig[Number(status)]?.text || '未知状态';
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '未知时间';
      try {
        let date = new Date(typeof timeStr === 'string' ? timeStr.replace(/T/g, ' ') : timeStr);
        if (isNaN(date.getTime())) return '无效时间';
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      } catch (e) {
        return timeStr.substring(0, 16).replace('T', ' ') || '未知时间';
      }
    },
    
    // 跳转到创建工单页面
    gotoCreateTicket() {
      uni.navigateTo({ url: '/pages/User/workorder/create' });
    },
    
    // 跳转到工单详情页
    gotoWorkorderDetail(id) {
      if (!id) return uni.showToast({ title: '工单ID无效', icon: 'none' });
      uni.navigateTo({ url: `/pages/User/workorder/detail?id=${id}` });
    },
    
    // 跳转到评价页面
    gotoRating(orderId, title, employeeName) {
      if (!orderId) return uni.showToast({ title: '工单ID无效', icon: 'none' });
      uni.navigateTo({ 
        url: `/pages/User/workorder/rating?orderId=${orderId}&title=${encodeURIComponent(title || '')}&employeeName=${encodeURIComponent(employeeName || '')}`,
        success: (res) => res.eventChannel.on('evaluateDone', () => {
          this.loadWorkorders(true);
          uni.$emit('workorderUpdated');
        })
      });
    },
    
    // 跳转到评价列表页
    gotoEvaluatePage() {
      uni.navigateTo({ url: '/pages/User/profile/evaluate' });
    },
    
    // 跳转到修改工单页面
    gotoEditTicket(item) {
      if (!item?.id) return uni.showToast({ title: '工单信息无效', icon: 'none' });
      const { id, title, des, phone, name, longitude, latitude, priorityType, pic } = item;
      const params = `id=${encodeURIComponent(id)}&title=${encodeURIComponent(title||'')}&des=${encodeURIComponent(des||'')}&phone=${encodeURIComponent(phone||'')}&name=${encodeURIComponent(name||'')}&address=${encodeURIComponent(`${latitude||''},${longitude||''}`)}&priorityType=${priorityType||1}&pic=${encodeURIComponent(pic||'')}&isEdit=true`;
      uni.navigateTo({ url: `/pages/User/workorder/create?${params}` });
    },
    
    // 显示删除确认弹窗
    showDeleteConfirm(id) {
      if (!id) return uni.showToast({ title: '工单ID无效', icon: 'none' });
      uni.showModal({
        title: '确认删除',
        content: '删除后不可恢复，是否继续？',
        confirmColor: '#ff4d4f',
        success: (res) => res.confirm && this.deleteWorkorder(id)
      });
    },
    
    // 执行删除工单
    async deleteWorkorder(id) {
      if (!id || this.isDeleting) return;
      this.isDeleting = true;
      try {
        await request.post(`/api/workOrderInfo/deleteWithPic?id=${id}`, {}, true);
        uni.showToast({ title: '删除成功', icon: 'success' });
        this.loadWorkorders(true);
        uni.$emit('workorderUpdated');
      } catch (error) {
        uni.showToast({ title: error.msg || '删除失败', icon: 'none' });
      } finally {
        this.isDeleting = false;
      }
    },
    
    // 核心：处理支付流程（已修复金额传递问题）
    async handlePay(orderId) {
      if (!orderId) return uni.showToast({ title: '工单ID无效', icon: 'none' });
      this.$set(this.isPaying, orderId, true);
      
      try {
        // 1. 第一步：获取后端计算的最终支付金额（必须调用calculateAmount接口）
        const amountRes = await this.getPaymentAmount(orderId);
        if (!amountRes.success) throw new Error(amountRes.msg || '获取支付金额失败');
        this.payAmount = amountRes.data;
        
        // 日志：确认获取的金额是否正确（应为1250.00）
        console.log('从calculateAmount接口获取的最终应支付金额:', this.payAmount);
        if (this.payAmount <= 0) {
          throw new Error(`无效金额：${this.payAmount.toFixed(2)}（金额必须大于0）`);
        }
        
        // 2. 第二步：用户确认支付（显示最终金额）
        const confirmPay = await this.showPayConfirm();
        if (!confirmPay) return;
        
        // 3. 第三步：传递orderId + 正确金额到process接口
        const prepayRes = await this.getPrepayParams(orderId, this.payAmount);
        if (!prepayRes.success) throw new Error(prepayRes.msg || '获取支付信息失败');
        const payParams = prepayRes.data;
        
        // 4. 第四步：调用微信支付
        const payResult = await uni.requestPayment({
          provider: 'wxpay',
          timeStamp: payParams.timeStamp + '',
          nonceStr: payParams.nonceStr,
          package: payParams.package,
          signType: payParams.signType || 'MD5',
          paySign: payParams.paySign
        });
        
        // 5. 第五步：确认支付状态
        if (payResult.errMsg === 'requestPayment:ok') {
          await this.confirmPaymentStatus(orderId);
        } else {
          uni.showToast({ title: '支付已取消', icon: 'none' });
        }
      } catch (err) {
        console.error('支付失败详情:', err);
        // 错误提示：明确金额相关问题
        const errorMsg = err.message.includes('金额') 
          ? `支付金额错误：${err.message}（请联系管理员）` 
          : err.message || '支付失败，请重试';
        uni.showToast({ title: errorMsg, icon: 'none', duration: 4000 });
      } finally {
        this.$set(this.isPaying, orderId, false);
      }
    },
    
    // 1. 获取最终支付金额（调用后端calculateAmount接口）
    getPaymentAmount(orderId) {
      return new Promise((resolve) => {
        request.post(
          '/api/payment/calculateAmount',
          { orderId },
          true
        ).then(res => {
          // 确保金额为数字类型且有效
          const finalAmount = Number(res);
          if (isNaN(finalAmount) || finalAmount <= 0) {
            return resolve({ success: false, msg: `获取金额无效：${res}（需为正数）` });
          }
          resolve({ success: true, data: finalAmount });
        }).catch(error => {
          resolve({ success: false, msg: `获取金额失败：${error.msg || error.message}` });
        });
      });
    },
    
    // 2. 传递正确金额到process接口（核心修复：添加amount参数）
    getPrepayParams(orderId, amount) {
      return new Promise((resolve) => {
        // 传递orderId和amount（与后端PaymentRequestDTO字段匹配）
        // 若后端字段名为payAmount，需改为payAmount: amount.toFixed(2)
        request.postJson(
          '/api/payment/process',
          { 
            orderId: orderId, 
            amount: amount.toFixed(2) // 强制保留两位小数，确保格式正确
          },
          true
        ).then(res => {
          if (res?.code === 0 && res?.data) {
            console.log('process接口返回的预支付参数:', res.data);
            resolve({ success: true, data: res.data });
          } else {
            resolve({ success: false, msg: res?.msg || '获取预支付参数失败' });
          }
        }).catch(error => {
          resolve({ success: false, msg: `调用支付接口失败：${error.msg || error.message}` });
        });
      });
    },
    
    // 3. 确认支付状态
    confirmPaymentStatus(orderId) {
      return new Promise((resolve) => {
        request.get(
          '/api/payment/getPayStatus',
          { orderId },
          true
        ).then(res => {
          if (res === 1) {
            uni.showToast({ title: '支付成功！', icon: 'success', duration: 2000 });
            setTimeout(() => {
              this.loadWorkorders(true);
              uni.$emit('workorderUpdated');
            }, 1000);
            resolve(true);
          } else {
            uni.showToast({ title: '支付结果确认中，请稍后查看', icon: 'none' });
            resolve(false);
          }
        }).catch(error => {
          uni.showToast({ title: '查询支付状态失败', icon: 'none' });
          resolve(false);
        });
      });
    },
    
    // 显示支付确认弹窗（明确显示最终金额）
    showPayConfirm() {
      return new Promise((resolve) => {
        uni.showModal({
          title: '确认支付',
          content: `请确认支付金额：¥${this.payAmount.toFixed(2)}`,
          confirmText: '确认支付',
          cancelText: '取消',
          confirmColor: '#165dff',
          success: (res) => resolve(res.confirm)
        });
      });
    }
  }
};
</script>

<style scoped>
/* 全局样式变量 */
:root {
  --primary-color: #165dff;
  --danger-color: #ff4d4f;
  --success-color: #00b42a;
  --warning-color: #ff9800;
  --text-primary: #272e3b;
  --text-secondary: #86909c;
  --border-radius: 8px;
  --box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

/* 页面容器 */
.container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 45px 0 120rpx;
  box-sizing: border-box;
}

/* 顶部导航栏 */
.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 45px;
  background-color: #5555ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--box-shadow);
  z-index: 99;
}
.nav-title {
  font-size: 18px;
  font-weight: 500;
}

/* 创建工单按钮 */
.create-btn-container {
  padding: 15px;
}
.create-btn {
  width: 100%;
  background-color: var(--primary-color);
  color: #fff;
  padding: 12px 0;
  border-radius: var(--border-radius);
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}
.create-btn .fa {
  margin-right: 8px;
}

/* 筛选栏 */
.filter-bar {
  background-color: #fff;
  padding: 10px 0;
  border-top: 1px solid #e5e6eb;
  border-bottom: 1px solid #e5e6eb;
  position: sticky;
  top: 45px;
  z-index: 90;
}
.filter-scroll {
  white-space: nowrap;
  padding: 0 15px;
}
.filter-items {
  display: inline-flex;
  gap: 10px;
}
.filter-btn {
  padding: 6px 15px;
  background-color: #f5f7fa;
  color: var(--text-secondary);
  border-radius: 20px;
  font-size: 14px;
  border: none;
}
.filter-btn.active {
  background-color: #e8f3ff;
  color: var(--primary-color);
  font-weight: 500;
}

/* 工单列表 */
.workorder-list {
  padding: 10px 15px;
}

/* 加载中状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: var(--text-secondary);
}
.loading-spinner {
  font-size: 60rpx;
  margin-bottom: 20rpx;
  animation: spin 1.5s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 工单列表项 */
.workorder-item {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: var(--box-shadow);
  cursor: pointer;
}

/* 工单项头部 */
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}
.item-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  flex: 1;
  margin-right: 10px;
  word-break: break-all;
}
.item-status {
  font-size: 12px;
  padding: 3px 8px;
  border-radius: 12px;
}

/* 状态样式 */
.status-pending { background-color: #fffbe6; color: #faad14; }
.status-processing { background-color: #e6f7ff; color: #1890ff; }
.status-handled { background-color: #f6ffed; color: var(--success-color); }
.status-settled { background-color: #e1bee7; color: #6a1b9a; }
.status-pending-review { background-color: #fff0f0; color: #fa541c; }
.status-archived { background-color: #f5f5f5; color: #8c8c8c; }

/* 工单描述 */
.item-desc {
  font-size: 14px;
  color: #4e5969;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 工单项底部 */
.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-time {
  font-size: 12px;
  color: var(--text-secondary);
}
.item-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
.handler-info {
  font-size: 12px;
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  gap: 3px;
}

/* 操作按钮 */
.edit-btn, .delete-btn, .rate-btn, .view-rate-btn, .pay-btn {
  font-size: 12px;
  padding: 3px 8px;
  border-radius: 4px;
  border: none;
  background: transparent;
  display: flex;
  align-items: center;
  gap: 3px;
}
.edit-btn { color: var(--primary-color); }
.delete-btn { color: var(--danger-color); }
.rate-btn, .view-rate-btn { color: var(--primary-color); }
.pay-btn { color: var(--warning-color); }

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}
.empty-icon {
  font-size: 60px;
  color: #ddd;
  margin-bottom: 20px;
}
.empty-text {
  color: var(--text-secondary);
  font-size: 14px;
  text-align: center;
}
</style>
